package com.cxl.price.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.htmlparser.util.ParserException;

import com.cxl.price.bean.Good;
import com.cxl.price.bean.Goods;
import com.cxl.price.bean.Imgs;
import com.cxl.price.bean.Shop;
import com.cxl.price.service.GoodService;
import com.cxl.price.service.GoodsService;
import com.cxl.price.service.ImgsService;
import com.cxl.price.service.ShopService;
import com.cxl.price.top.service.TopItemResponseService;
import com.cxl.price.util.ImageUtil;
import com.summer.core.action.BaseAction;
import com.summer.core.bean.Pager;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemImg;
import com.taobao.api.domain.SellerCat;
import com.taobao.api.request.ItemImgDeleteRequest;
import com.taobao.api.request.ItemImgUploadRequest;
import com.taobao.api.request.ItemRecommendAddRequest;
import com.taobao.api.request.ItemRecommendDeleteRequest;
import com.taobao.api.request.ItemUpdateDelistingRequest;
import com.taobao.api.request.ItemUpdateRequest;
import com.taobao.api.request.ItemsInventoryGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.SellercatsListGetRequest;
import com.taobao.api.response.ItemImgDeleteResponse;
import com.taobao.api.response.ItemImgUploadResponse;
import com.taobao.api.response.ItemUpdateDelistingResponse;
import com.taobao.api.response.ItemUpdateResponse;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.SellercatsListGetResponse;


@ParentPackage("price")
public class GoodsAction extends BaseAction<Goods, GoodsService> {
	

	private ShopService shopservice;
	
	
	private TopItemResponseService topItemResponseService;
	
	private GoodService goodService;
	
	private List<Shop> shopList;
	
	private ImgsService imgsService;
	
	public List<Shop> getShopList() {
		return shopList;
	}
	public void setShopList(List<Shop> shopList) {
		this.shopList = shopList;
	}
	public ShopService getShopservice() {
		return shopservice;
	}
	@Resource
	public void setShopservice(ShopService shopservice) {
		this.shopservice = shopservice;
	}
	
	@Resource
	public void setGoodService(GoodService goodService) {
		this.goodService = goodService;
	}
	@Resource
	public void setTopItemService(TopItemResponseService topItemResponseService) {
		this.topItemResponseService = topItemResponseService;
	}
	
	@Resource
	public void setImgsService(ImgsService imgsService) {
		this.imgsService = imgsService;
	}
	public Goods getGoods()
	{
		return bean;
	}
	

	public void setGoods(Goods goods) {
		this.bean=goods;
	}

	@Resource
	public void setService(GoodsService service) {
		this.service = service;
	}
	
	
	public String save() {
		
		if (bean == null) {
			return ERROR;
		}
		bean.setCreateDate(new Date());
		return super.save();
		
	}
	
	
	@Override
	public String list() throws Exception {
		  SellercatsListGetResponse response=topBaseService.getTaobaoResponse(SellercatsListGetRequest.class,getRequest());
	       List<SellerCat> SellerCatList= response.getSellerCats();
	       getRequest().setAttribute("catList", SellerCatList);
	  //     System.out.println(pager.getSearchMap().get("seller_cids"));
		
	shopList=shopservice.getAll();
	pager=(pager==null?new Pager():pager);
	pager.setOrderBy("volume");
	pager.getSearchType().put("price", "geProperty");
	pager.getSearchType().put("pinpai", "empty");
	pager.getSearchType().put("good", "empty");
	pager.getSearchType().put("seller_cids", "like");
	if(bean!=null&&bean.getPrice()!=null)
	{
		pager.getSearchMap().put("price","new_price");
		pager.getSearchType().put("price", "geProperty");
	}
	return super.list();
	}
	
	/**
	 * 编辑商品   如 价格 描述 标题 变化则 同步标志为false;
	 */
	public String update() {
		if (bean == null) {
			return ERROR;
		}
		Goods goods=service.get(bean.getId());
		goods.setPinpai(bean.getPinpai());
		goods.setXinghao(bean.getXinghao());
		if(!bean.getPrice().equals(goods.getPrice())||!goods.getName().equals(bean.getName())||!bean.getDescription().equals(bean.getDescription()))
		{
			goods.setSynch(false);
			goods.setPrice(bean.getPrice());
			goods.setDescription(bean.getDescription());
			goods.setName(bean.getName());
		}
		bean=goods;
		return super.update();
	}
	
	
	public String updata_price() throws ApiException, ParseException
	{
		List<Goods> goods=new ArrayList();
		if(ids==null)
		{
			goods=service.getAll();
		}
		else
		{
			for(String id:ids)
			{
				goods.add(service.get(id));
			}
		}
		for(Goods good:goods)
		{
			ItemUpdateRequest request=new ItemUpdateRequest();
			request.setTitle(good.getName());
			request.setNumIid(good.getNum_iid());
			if(good.getNew_price()!=null&&good.getPrice()<good.getNew_price())
			{
				request.setPrice((good.getNew_price()+5)+"");
			
			}
			topItemResponseService.getItemUpdateResponse(request);
		}
		
		redirectionUrl ="goods!list.action";
		//return ajaxJsonSuccessMessage("更新成功");
		
		return SUCCESS;
	}
	
	//寻找匹配的url　matchgood =true 锁定的不匹配
	public String serachUrl() throws UnsupportedEncodingException
	{
		if(pager==null)
		{
			pager=new Pager();
		}
		pager.setIs_all(true);
		
		shopList=shopservice.getAll();
		/**
		 * 暂时屏蔽2个商店
		 */
	//	shopList.remove(1);
		//shopList.remove(1);
		List<Goods> goodsAll=new ArrayList<Goods>();
		if(ids==null)
		{
			//所有商品
			goodsAll=service.findByPager(pager).getList();
		}
		else
		{
			for(int i=0;i<ids.length;i++)
			{
				goodsAll.add(service.get(ids[i]));
			}
		}
		//匹配商品 寻找url
		try
		{
		service.addSearchAllShopAndImport(shopList,goodsAll);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		//匹配价格最低的商店，或者匹配指定商店
		for(Goods goods:goodsAll)
		{
			service.clear();//清除session缓存
			goods=service.get(goods.getId());
			goods.setNew_price(goodService.getMinPrice(goods));
			if(goods.isMatchGood()==false)
			{
			//未有锁定才去匹配
			service.update(goods);
			}
		}
		redirectionUrl ="goods!list.action";
		return SUCCESS;
	}
	
	/**
	 * 导入淘宝商店商品（商品同步）
	 * @return
	 * @throws ApiException
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public String import_goods() throws Exception
	{
		
		//同步在售
		ItemsOnsaleGetResponse onsale=topBaseService.getTaobaoResponse(ItemsOnsaleGetRequest.class, getRequest());
		
		List<Item> list=onsale.getItems();
//		if(onsale.getTotalResults()>200L)
//		{
//			ItemsOnsaleGetRequest def=new ItemsOnsaleGetRequest();
//			Long pageTotle=onsale.getTotalResults()/200L+(onsale.getTotalResults()%200L>0?1:0);
//			while(pageTotle>1L)
//			{
//				def.setPageNo(pageTotle);
//				onsale=topBaseService.getTaobaoResponse(def,getRequest());
//				list.addAll(onsale.getItems());
//				pageTotle=pageTotle-1;
//			}
//		}
	
		//同步库存
//		ItemsInventoryGetResponse inventory=topItemResponseService.getItemsInventoryGetResponse();
//		if(inventory.getItems()!=null)
//		{
//		list.addAll(inventory.getItems());
//		
//		if(inventory.getTotalResults()>200L)
//		{
//			ItemsInventoryGetRequest def=new ItemsInventoryGetRequest();
//			Long pageTotle=inventory.getTotalResults()/200L+(inventory.getTotalResults()%200L>0?1:0);
//			while(pageTotle>1L)
//			{
//				def.setPageNo(pageTotle);
//				inventory=topItemResponseService.getItemsInventoryGetResponse(def);
//				list.addAll(inventory.getItems());
//				pageTotle=pageTotle-1;
//			}
//		} 
//		}
		service.addTaoBaoGoods(list,getRequest());
	
		redirectionUrl ="goods!list.action";
		return SUCCESS;
	}
	
	/**
	 * 商品下架
	 * @return
	 * @throws ParseException 
	 * @throws ApiException 
	 * @throws ApiException
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public String delisting() throws ApiException, ParseException 
	{
		if(ids==null)
		{
			//goods=service.getAll();
		}
		else
		{
			ItemUpdateDelistingRequest req=new ItemUpdateDelistingRequest();
			for(String id:ids)
			{
				Goods goods=service.get(id);
				if("onsale".equals(goods.getOnSale()))
				{
					ItemUpdateDelistingResponse res=topItemResponseService.getItemUpdateDelistingResponse(goods.getNum_iid());
				if(res==null&&res.getItem()==null)
				{
					return ERROR;
				}
				goods.setOnSale("instock"); //本机下架
				}
				service.update(goods);
			}
		}
		redirectionUrl ="goods!list.action";
		return SUCCESS;
	}
	
	/**
	 * 商品上架
	 * @return
	 * @throws ParseException 
	 * @throws ApiException 
	 * @throws ApiException
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public String listing() throws ApiException, ParseException 
	{
		if(ids==null)
		{
			//goods=service.getAll();
		}
		else
		{
			ItemUpdateDelistingRequest req=new ItemUpdateDelistingRequest();
			for(String id:ids)
			{
				Goods goods=service.get(id);
				if("instock".equals(goods.getOnSale()))
				{
				topItemResponseService.getItemUpdateListingResponse(goods.getNum_iid(),100L);
				goods.setOnSale("onsale"); 
				}
				service.update(goods);
			}
		}
		redirectionUrl ="goods!list.action";
		return SUCCESS;
	}
	
	
	/**
	 * 删除淘宝商品（删除淘宝网的本机同时删除）
	 * @return
	 */
	public String delete_goods()
	{
		List<Goods> goodsList=service.getAll();
		
		for(Goods goods:goodsList)
		{
			
		}
		
		redirectionUrl ="goods!list.action";
		return SUCCESS;
	}
	
	/**
	 * ajax 模糊搜索商品名称
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String searchName() throws UnsupportedEncodingException
	{
		//new String(bean.getName().getBytes("ISO-8859-1"),"UTF-8")
		Pager page=new Pager();
		page.setProperty("name");
		page.setKeyword(bean.getName());
		List<Goods> list=service.findByPager(page).getList();
		JsonConfig config = new JsonConfig();
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object arg0, String arg1, Object arg2) {
                if (arg1.equals("good")||arg1.equals("mainGood")||arg1.equals("seller_cids")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        JSONArray jsonObject = JSONArray.fromObject(list,config);
        String content=jsonObject.toString();
		return ajaxJson(content);
		
	}
	
	/**
	 * 点淘宝图片转到淘宝链接。图片信息没有 先下载
	 * @return
	 * @throws ApiException
	 */
	public String getTaoBaoGoodsUrl() throws ApiException 
	{
		Goods goods=service.get(bean.getId());
		String tb_url=goods.getTb_url();
		if(tb_url==null)
		{
		Item item=topItemResponseService.getItemGetResponse(bean.getNum_iid()).getItem();
		tb_url=item.getDetailUrl();
		List<ItemImg> imgs=item.getItemImgs();
		
		
		//myImg.set
		Set<Imgs> set=goods.getImgsSet();
		Iterator<Imgs> iter=set.iterator();
		for(ItemImg img:imgs)
		{
			boolean has=false;
			Imgs myImg=new Imgs();
			myImg.setImg_url(img.getUrl());
			while(iter.hasNext())
			{
				if(iter.next().getImg_url().equals(img.getUrl()))
				{
					has=true;
				}
			
			}
			if(!has)
			{
				goods.addImgs(myImg);
			}
		}
		/**
		 * 利用客户查询的时候更新相关信息
		 */
		goods.setTb_url(tb_url);
		goods.setDescription(item.getDesc());
		goods.setPrice(Double.parseDouble(item.getPrice()));
		goods.setProduct_id(item.getProductId());
		goods.setSynch(true);
	//	goods.setVolume(item.getVolume());
		
		String propsName[]=item.getPropsName().split(";");
		String total="";
		for(String pr:propsName)
		{
			String cc[]=pr.split(":");
			if(cc.length==4)
			{
				total+=cc[2]+":"+cc[3]+";";
			}
			
		}
		goods.setPropsName(total);
		
		service.update(goods);
		}
	
		return ajaxJson(tb_url);
	}
	
	/**
	 * 编辑   如没有描述 和图片数据 则 同步数据（下载数据）
	 * @throws ApiException 
	 */
	public String edit()  {
		shopList=shopservice.getAll();
		Goods goods=service.get(id);
		if(StringUtils.isEmpty(goods.getPropsName()))
		{
		 Long num_iid=goods.getNum_iid();
		try {
			Item item=topItemResponseService.getItemGetResponse(num_iid).getItem();
			goods.setName(item.getTitle());
			goods.setPrice(Double.parseDouble(item.getPrice()));
			goods.setNum(item.getNum());
			goods.setTb_img(item.getPicUrl());
			goods.setDescription(item.getDesc());
			goods.setTb_url(item.getDetailUrl());
			goods.setOnSale(item.getApproveStatus());
			goods.setProduct_id(item.getProductId());
		//	goods.setVolume(item.getVolume());
			goods.setSynch(true);
			
			
			String propsName[]=item.getPropsName().split(";");
			String total="";
			for(String pr:propsName)
			{
				String cc[]=pr.split(":");
				if(cc.length==4)
				{
					total+=cc[2]+":"+cc[3]+";";
				}
				
			}
			goods.setPropsName(total);
			
			List<ItemImg> imgs=item.getItemImgs();
			//myImg.set
			Set<Imgs> set=goods.getImgsSet();
			Iterator<Imgs> iter=set.iterator();
			for(ItemImg img:imgs)
			{
				boolean has=false;
				Imgs myImg=new Imgs();
				myImg.setImg_url(img.getUrl());
				myImg.setImg_id(img.getId());
				myImg.setGoods(goods);
				while(iter.hasNext())
				{
					if(iter.next().getImg_url().equals(img.getUrl()))
					{
						has=true;
					}
				
				}
				if(!has)
				{
					goods.addImgs(myImg);
				}
			}
			service.update(goods);
			
		} catch (ApiException e) {
			e.printStackTrace();
		}
		}
		bean=service.load(id);
		return result(INPUT);
	}
	
	/**
	 * 同步本地数据给淘宝 （修改价格 名称 描述）
	 * @return
	 * @throws ApiException
	 * @throws ParseException
	 */
	public String synch() throws ApiException, ParseException
	{
		Goods goods=service.get(id);
		ItemUpdateRequest updateRes=new ItemUpdateRequest();
		updateRes.setNumIid(goods.getNum_iid());
		updateRes.setPrice(goods.getPrice()+"");
		updateRes.setDesc(goods.getDescription());
		updateRes.setTitle(goods.getName());
		ItemUpdateResponse  res=topItemResponseService.getItemUpdateResponse(updateRes);
		if(res.getMsg()!=null)
		{
			return ERROR;
		}
		goods.setSynch(true);
		service.update(goods);
		redirectionUrl ="goods!list.action";
		return SUCCESS;
	}
	
	/**
	 * 修改已经匹配商品的 关键字段
	 * @return
	 * @throws ApiException
	 * @throws ParseException
	 */
	public String goMatch() throws ApiException, ParseException
	{
		boolean match=bean.isMatchGood();
		
		if(ids==null)
		{
			return ERROR;
		}
		
			for(String id:ids)
			{
			 Goods goods=	service.get(id);
			 goods.setMatchGood(match);
			 service.update(goods);
			}
		redirectionUrl ="goods!list.action";
		return SUCCESS;
	}
	
	public String updateGoodprice() throws InstantiationException, IllegalAccessException, ClassNotFoundException, ParserException
	{
		String shop_id=getRequest().getParameter("shopid");
		//shop_id为空  表示更新 main 
		if(ids==null)
		{
			List<Goods> list=service.getAll();
			ids=new String[list.size()];
			int i=0;
			for(Goods goods:list)
			{
				ids[i]=goods.getId();
			}
		}
			for(String id:ids)
			{
				Goods goods=	service.get(id);
				Set<Good> goodSet=goods.getGood();
				
				//选出要更新的 good
				Iterator<Good> iter=goodSet.iterator();
				while(iter.hasNext())
				{
					Good good=iter.next();
					if((StringUtils.isEmpty(shop_id)&&good.isIs_master())||(!StringUtils.isEmpty(shop_id)&& good.getShop().getId().equals(shop_id)))
					{
						goodService.updatePrice(good);
					}
				}
			}
		redirectionUrl ="goods!list.action";
		return SUCCESS;
		
	}
	
	/*
	 * 更新交易量
	 */
	/**
	 * @return
	 * @throws ApiException
	 */
	public String updateVolume() throws ApiException
	{
//		ItemsSearchRequest def=new ItemsSearchRequest();
//		def.setNicks(SummerGlobals.getProperty("top.nick"));
//		def.setPageSize(100L);
//		List<Item> listItem=topItemResponseService.getItemsSearchResponse(def).getItemSearch().getItems();
//		for(Item item:listItem)
//		{
//			Long num_iid=item.getNumIid();
//			Goods goods=service.get("num_iid",num_iid);
//			if(goods!=null)
//			{
//				goods.setVolume(item.getVolume());
//				service.update(goods);
//			}
//			
//			
//		}
		
		
		return result(LIST);
	}
	
	public String upImg() throws Exception 
	{
				String url=getRequest().getParameter("img_url");
				Goods goods=service.get(id);
				ItemImgUploadRequest def=new ItemImgUploadRequest();
				def.setNumIid(goods.getNum_iid());
				String fileName=new ImageUtil().saveToFile(url, "tempUp");
				FileItem fItem = new FileItem(new File(fileName+".jpg"));
				def.setImage(fItem);
				ItemImgUploadResponse resp=topItemResponseService.getItemImgUploadResponse(def);
				
				Imgs img=new Imgs();
				img.setImg_id(resp.getItemImg().getId());
				img.setGoods(goods);
				img.setImg_url(resp.getItemImg().getUrl());
				new ImageUtil().deleteFile("tempUp.jpg");
				goods.addImgs(img);
		service.update(goods);
		return ajaxJsonSuccessMessage("上传成功！");
	}
	
	public String delImg() throws Exception 
	{
				Long num_iid =Long.parseLong(getRequest().getParameter("num_iid"));
				Long img_id=Long.parseLong(getRequest().getParameter("img_id"));
//				Goods goods=service.get(id);
				ItemImgDeleteRequest   def=new ItemImgDeleteRequest();
				def.setNumIid(num_iid);
				def.setId(img_id);
				ItemImgDeleteResponse resp=topItemResponseService.getItemImgDeleteResponse(def);
				
				imgsService.delete(imgsService.get("img_id",img_id));
				
				
//		service.update(goods);
		return ajaxJsonSuccessMessage("删除成功！");
	}
	
	
	//橱窗推荐操作
	public String showCaseOpt() throws ApiException
	{
		String type=getRequest().getParameter("type");
		if("add".equals(type))
		{
			
		}
		else if("delete".equals(type))
		{
			
		}
		else
		{
			//前40名橱窗推荐 先取消推荐了的
			List<Goods> goodsList=service.getListByHql("from Goods where hasShowCase =true");
			//销售好的前40名
			List<Goods> sellsGood=service.getListByHql("from Goods where volume>0 order by volume desc limit 40");
			 
			ItemRecommendDeleteRequest def=new ItemRecommendDeleteRequest();
			for(Goods good:goodsList)
			{
				def.setNumIid(good.getNum_iid());
				topItemResponseService.getItemRecommendDeleteResponse(def);
			}
			
			ItemRecommendAddRequest def1=new ItemRecommendAddRequest();
			for(Goods goods:sellsGood)
			{
				def1.setNumIid(goods.getNum_iid());
				
				topItemResponseService.getItemRecommendAddResponse(def1);
			}
		}
		
		return result(LIST);
		
	}
	
	public static void main(String[] args) {
		
		Map a=new HashMap();
		a.put("b","11111");
		a.put("b","2");
		System.out.println(a.get("b"));
	}
	
	
}
